/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
/**
 * @file created by ljh 2020/08/19.
 * ipv4或ipv4:port
 * 对ip进行严格的校验（多播地址，广播地址，网络地址，E类地址，首尾不能为0等等）
 */

/**
 * 多行IP地址范围校验
 * */
import {
    htmlEncode,
    ip2int
} from '../../format';
import checkIp from './ip';
const DEFAULT_MAXLINE = 50;
const DEFAULT_MAXRANGE = 2;

function ipRangeMulti (value, option) {
    option = option || {};
    let array;
        let errList = [];
        let maxline = option.maxline || DEFAULT_MAXLINE;
        let ipRule = {
            check: option.check || '!lookback,!multicast,!broadcast',
            netmask: option.netmask
        };

    array =  value.split('\n');

    if (maxline && array.length > maxline) {
        errList.push(_('此IP范围最多支持{0}行', maxline));
        return errList;
    }

    array.forEach((item, index) => {

        let ip = item.replace(/(^\s*)|(\s*$)/g, '');
            let errMsg = _('第{0}行（{1}）格式错误：', (index + 1), htmlEncode(item));
            let rang;

        if (!ip) {
            return;
        }

        if (ip.indexOf('-') > -1) {
            rang = ip.split('-');

            if (rang.length !== DEFAULT_MAXRANGE) {
                errList.push(errMsg + _('IP范围不支持多个“-”') + '</br>');
                return;
            }

            if (checkIp.validate(rang[0], ipRule) !== true) {
                errList.push(errMsg + (checkIp.validate(rang[0], ipRule) || _('IP格式有误！')) + '</br>');
                return;
            }

            if (checkIp.validate(rang[1], ipRule) !== true) {
                errList.push(errMsg + (checkIp.validate(rang[1], ipRule) || _('IP格式有误！')) + '</br>');
                return;
            }

            if (ip2int(rang[0]) - ip2int(rang[1]) > 0) {
                errList.push(errMsg + _('IP范围的右值应大于左值') + '</br>');
                return;
            }

        } else if (checkIp.validate(ip, ipRule) !== true) {
            errList.push(errMsg + (checkIp.validate(ip, ipRule) || _('IP格式有误！')) + '</br>');
        }

    });

    return errList.length ? errList : true;
}

export default ipRangeMulti;
